<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>POI Collector</title>
<script type="text/javascript" charset="utf-8" src="ext/phonegap/phonegap.js.base"></script>
<script type="text/javascript" charset="utf-8" src="ext/phonegap/geolocation.js"></script>
<script type="text/javascript" src="ext/jqtouch/jquery.1.3.2.min.js"></script>
<script type="text/javascript" src="ext/jqtouch/jqtouch.min.js"></script>
<script type="text/javascript" src="ext/extensions/jqt.floaty.js"></script>
<script type="text/javascript" src="ext/extensions/jquery.base64.js"></script>
<script type="text/javascript" src="ext/extensions/jquery.base64.js"></script>
<script src="http://code.google.com/apis/gears/gears_init.js"
	type="text/javascript"></script>
<script src="ext/geo-location-javascript/geo.js" type="text/javascript"></script>
<script src="settings.js" type="text/javascript"></script>
<script src="classes.js" type="text/javascript"></script>
<script type="text/javascript" src="ext/openlayers/OpenLayers.js"></script> 
<style type="text/css" media="screen">
@import "ext/jqtouch/jqtouch.css";
</style>
<style type="text/css" media="screen">
@import "ext/themes/jqt/theme.min.css";
</style>
<style type="text/css" media="screen">
@import "app.css";
</style>

<script type="text/javascript" charset="utf-8">

		//application attributes, like version, app name, author
		var app = {name: 'OSM Mobile POI Collector', author: 'Paweł Niechoda', version: '1.0'};

	    //global application variables
	    var global = {};
	    global.floatWidget = null;
	    global.dialogWindow = null;
	    global.waitingWidget = null;
	    global.editForm = null;
	    global.user = {login: "", password: "", changegSetId: 0};
	    global.poi = null;
	    global.map = new Map();
	    global.newPoiMarker = new Marker('newPoiMarker', settings.newPoiIcon);
	    global.coordinates = {lon: null, lat: null};
	    global.map.Click = null;
	    global.pois = new PoiSet();
	    global.follow = false;
	    global.zoom = 18;
	    global.currentLocationMarker = new Marker('currentLocationMarker', settings.currentLocationIcon);
		global.watchId = 0;

		var checkedFollowBtnBackgroundImage = 'url(img/checkbox_checked.png), -webkit-gradient(linear, 0% 0, 0% 100%, from(#4C4D4E), to(#404142))';
		var uncheckedFollowBtnBackgroundImage = 'url(img/checkbox_unchecked.png), -webkit-gradient(linear, 0% 0, 0% 100%, from(#4C4D4E), to(#404142))';

		var jqt;
		//preparing jQTouch object, preloading images
		jqt = $.jQTouch({
			preloadImages: [
		    	'ext/themes/jqt/img/chevron_white.png',
		        'ext/themes/jqt/img/bg_row_select.gif',
				'ext/themes/jqt/img/back_button_clicked.png',
				'ext/themes/jqt/img/button_clicked.png',
				'img/checkbox_unchecked.png',
				'img/checkbox_checked.png'
			]
		});

		var getInitalLocation = function() {
			//tries get initial location
			/*if (global.coordinates.lat == null || global.coordinates.lon == null) {
				global.coordinates = {lon: 0.003316, lat: 51.501727};
				var sucGetLoc = function(loc) {
					global.coordinates.lon = loc.coords.longitude;
					global.coordinates.lat = loc.coords.latitude;
			        global.map.centerTo(global.coordinates.lon, global.coordinates.lat, global.zoom);
				};

				var failGetLoc = function() {};
			
				if(geo_position_js.init()){
					geo_position_js.getCurrentPosition(sucGetLoc, failGetLoc);
				}
			}*/
		}
		


		//part openlayers dependent
		OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
            defaultHandlerOptions: {
                'single': true,
                'double': false,
                'pixelTolerance': 0,
                'stopSingle': false,
                'stopDouble': false
            },

            initialize: function(options) {
                this.handlerOptions = OpenLayers.Util.extend(
                    {}, this.defaultHandlerOptions
                );
                OpenLayers.Control.prototype.initialize.apply(
                    this, arguments
                ); 
                this.handler = new OpenLayers.Handler.Click(
                    this, {
                        'click': this.trigger
                    }, this.handlerOptions
                );
            }, 

            trigger: function(e) {
            	var lonLat = global.map.touchMap.getLonLatFromViewPortPx(e.xy).transform(global.map.displayProjection, global.map.calculateProjection);
            	global.newPoiMarker.putOnMap(lonLat.lon, lonLat.lat);
            }
			
        });

		var displayEditPoisBtns = function() {
	    	if (global.poi != null && global.poi.id == null) {
	        	$("#goToAddFrom").css('display','inherit');
		    	$("#logoutBtn").css('display', 'none');
		    	$("#cancelBtn").css('display', 'inherit');
		    	global.mapClick.activate(); //openlayers dependent line
	    	} else {
	    		$("#goToAddFrom").css('display','none');
		        $("#logoutBtn").css('display', 'inherit');
		        $("#cancelBtn").css('display', 'none');
		        global.mapClick.deactivate();//openlayers dependent line
		    } 
		}
  
        var preparePickUpCategoryScreen = function() {
			for (i in settings.poiCategories) {
				$("#pickUpCategoryList").append('<li class="formRow arrow"><a href="#typeScreen">' +  settings.poiCategories[i].name + '<span class="hide value">' + i + '</span></a></li>');
			}
        }

        var preparePickUpTypesScreen = function(category) {
            category = category.toLowerCase();
			$("#pickUpTypeList").html("");
			var types = settings.poiCategories[category].content;
			for (i in types) {
				$("#pickUpTypeList").append('<li class="formRow"><a class="typeName" href="#editingScreen">'
				+  types[i].name + '</a><span class="tagValue" style="display: none">' + types[i].tagValue
				+ '</span><span class="tagKey" style="display: none">' +  types[i].tagKey + '</span> </li>');
			}
			$("#pickUpTypeList li").click(function() {
				$("#typeName").html($(this).children(".typeName").text());
				$("#typeValue").html($(this).children(".tagValue").text());
				$("#typeTag").html($(this).children(".tagKey").text());
			});
        }
        
      	//handling getting current location
      	var startGeotracking = function(){
			try {
				var geolocationSuccess = function(position){
					global.coordinates.lon = position.coords.longitude;
    	    		global.coordinates.lat = position.coords.latitude;
				};
				var geolocationError = function(){
				};
				var options = { frequency: settings.gpsFrequency };
				global.watchId = navigator.geolocation.watchPosition(geolocationSuccess,
	                                                  geolocationError, options);
			} catch (e) {
				alert('geotracking error ' + e);
			}
      	}

      	var stopGeotracking = function() {
          	try {
      			navigator.geolocation.clearWatch(global.watchId);
          	} catch (e) {
				alert('geotracking error ' + e);
            }
        }

        
		//Sending data to server
        //update current poi
        var saveEditedPoi = function() {
            try {
			global.waitingWidget.message = message.floats.savingPoi;
			global.waitingWidget.wait();
			global.poi.data = global.editForm.getData();
			if (global.poi.id == null) {//sets coordinates, as it's new one
				global.poi.lon = global.newPoiMarker.getLon();
				global.poi.lat = global.newPoiMarker.getLat();
			}
			var createPoiSavingXML = function(poi){
				var poiDataString = '<osm><node ';
				if (global.poi.id != null) {
					poiDataString = poiDataString + ' id="' + global.poi.id + '" version="' + global.poi.version + '" ' ;
				}
				poiDataString = poiDataString + ' changeset="' + global.user.changeSetId +  '" lon="' + global.poi.lon + '" lat="' + global.poi.lat + '">';
				for (key in global.poi.data) {
					if (global.poi.data[key] != undefined && global.poi.data[key].length > 0) {
						poiDataString = poiDataString + '<tag k="' + key + '" v="' + global.poi.data[key] + '" />';
					}
				}
				poiDataString = poiDataString + "</node></osm>";
				return poiDataString;
			};
			xml = createPoiSavingXML(global.poi);
			//displays error communicate
			var fail = function(request, textStatus, errorThrown) {
				global.floatWidget.display(message.floats.failPoiSave);
				global.waitingWidget.stop();
			};
			var ok = function(data, textStatus, request) {
				try {
				var value =  parseInt(data);
				if (!isNaN(value)) {
					if (global.poi.marker.marker != null) {
						global.poi.marker.hide();
					}
					if (global.poi.id == null) {//sets id of just added poi
						global.poi.id = value;
						global.poi.version = 1;
	
					} else { //updates version of the poi
						global.poi.version = value;
					}
					global.poi.marker = new Marker(global.poi.id, global.poi.getIcon());
					global.poi.marker.init(global.map);
					global.poi.marker.putOnMap(global.poi.lon, global.poi.lat);
					global.pois.put(global.poi); 
					var poi = global.poi;
					global.poi.marker.setClickEvent(function() {
						global.dialogWindow.display();
						global.dialogWindow.setData({id: poi.id, name: poi.data.name, type: poi.getType().name});
						global.dialogWindow.setClickHandle(function() {
					    	global.poi = poi;
					    	jqt.goTo("#editingScreen");
					    	global.editForm.fill(poi);
						});
					});
					global.poi = null;
			    	displayEditPoisBtns(); 
					jqt.goTo("#mapScreen");
					global.floatWidget.display(message.floats.successPoiSave);	
				} else {
					fail();		
				}
				global.waitingWidget.stop();
				} catch (error) {
					alert(error);
		        }
			};
			var url;
			if (global.poi.id != null) {
				url = server.updateNodeUrl + global.poi.id;
			} else {
				url = server.createNodeUrl;
			}
			$.ajax({url: url, dataType: 'text', type: server.requestType,
				success: ok, error: fail, processData: false, data: xml,
				beforeSend: function(request) {
					request.setRequestHeader('Authorization',  'Basic ' + $.base64Encode(global.user.login + ':' + global.user.password));
				}
			});
            } catch (error) {
				alert(error);
            }
        }

        //log to osm account
        var logToServer = function() {
            try {
			global.waitingWidget.message = message.floats.loggingIn;
			global.waitingWidget.wait();
			global.user.login = $("#loginArea input[name=login]").val();
			global.user.password = $("#loginArea input[name=password]").val();
			var fail = function(request, textStatus, errorThrown) {
				global.floatWidget.display(message.floats.failLogin);
				global.waitingWidget.stop();
			};
			//gets id of current changeset, display comunicats, set map to current location, redirect to new screen
			var ok = function(data, textStatus, request) {
				var value =  parseInt(data);
				if (!isNaN(value)) { //checks if server respond with id of changeset
					global.user.changeSetId = value;
					global.floatWidget.display(message.floats.successLogin);
					jqt.goTo("#mapScreen");
					getInitalLocation();
					setTimeout(startGeotracking, 5000);
				} else {
					fail();		
				}
				global.waitingWidget.stop();
			};
			
			createChangeSetString= '<osm version="0.6" generator="Mobile POI Collector"><changeset>' +
            '<tag k="created_by" v="POI Collector v1.0"/> ' +
            '</changeset></osm>';
			$.ajax({url: server.createChangesetUrl, dataType: 'text', type: server.requestType,
				success: ok, error: fail, processData: false, data: createChangeSetString,
				beforeSend: function(request) {
					request.setRequestHeader('Authorization',  'Basic ' + $.base64Encode(global.user.login + ':' + global.user.password));
				}
			});
            } catch (e) {
				alert(e);
            }
        }

		

        
        //shows on map already existing pois (removes old ones)
		var showExistingPois = function() {
			try {
			var fail = function(request, textStatus, errorThrown) {
				ok(data, textStatus)
			};
			var ok = function(data, textStatus, request) {
				$(data).find('node').each(function(){
					try {
					var poi = new Poi();
					poi.id = $(this).attr('id');
					if (global.pois.has(poi.id)) {
						return;
					}
					poi.lon = $(this).attr('lon');
					poi.lat = $(this).attr('lat');
					poi.version = $(this).attr('version');
					$(this).find('tag').each(function(){
						var key = $(this).attr('k');
						var value = $(this).attr('v');
						poi.data[key] = value;
					});
					if (!poi.getType()) {
						return;
					}
					//var lonLat = new OpenLayers.LonLat(poi.lon, poi.lat);
					//var icon = new OpenLayers.Icon(settings.poiIconsFolder + poi.getIcon(),new OpenLayers.Size(32,27), new OpenLayers.Pixel(-(32/2), -27)); 
					//poi.marker = new OpenLayers.Marker(lonLat.clone().transform(calculateProjection, map.getProjectionObject()), icon);
					poi.marker = new Marker(poi.id, poi.getIcon());
					global.pois.put(poi);
					poi.marker.init(global.map);
					poi.marker.putOnMap(poi.lon, poi.lat);
					poi.marker.setClickEvent(function() {
						global.dialogWindow.display();
						global.dialogWindow.setData({id: poi.id, name: poi.data.name, type: poi.getType().name});
						global.dialogWindow.setClickHandle(function() {
					    	global.poi = poi;
					    	jqt.goTo("#editingScreen");
					    	global.editForm.fill(poi);
						});
					});
					} catch (err) {
						alert(err);
					}
				});
			};		
			var complete = function(request, textStatus) {
				ok(request.responseText, textStatus);
			};
			var boundary = global.map.getBoundary();
			$.ajax({url: server.getPoisByBBOXUrl + boundary.toBBOX(), dataType: 'xml',
				complete: complete, processData: false
			});
			} catch (error) {
				alert(error);
			}
		}
        //runs applicaion, this funciton is execute in infinite loop
		function runApp() {
			//if map screen is current one
			if ($('#mapScreen').hasClass('current')) {
				//getLocation();
				if (global.follow) {
					global.map.centerTo(global.coordinates.lon, global.coordinates.lat);
				}
				global.currentLocationMarker.putOnMap(global.coordinates.lon, global.coordinates.lat);
				if (global.map.hasMoved()) {
					if (global.map.getZoom() >= 17) {
						showExistingPois();
					}
				}
			}
		}
		
		//main function, is executed after whole page is loaded  
		function init(){
	      //sets layout properties
	      var bottomHeight = 35;
	      var toolbarHeight= 45;
	      var height = window.innerHeight;
	      var mapWidth = window.innerWidth;
	      var mapHeight = height - bottomHeight - toolbarHeight - 45;
		  $("#viewer").css('width', "100%");
		  $("#viewer").css('height', mapHeight + "px");
		  preparePickUpCategoryScreen();


	  	  global.map.touchMap = new OpenLayers.Map("viewer", {
	            controls: [
	                       new OpenLayers.Control.Navigation(),
	                       new OpenLayers.Control.PanPanel({slideFactor: Math.round(mapWidth / 8)}),
	                       new OpenLayers.Control.ZoomBox(),
	                       new OpenLayers.Control.ScaleLine(),
	                       new OpenLayers.Control.ZoomPanel()
	                   ]
	      });  
          //creates map
          /*map = new OpenLayers.Map("map", {
            controls: [
                new OpenLayers.Control.Navigation(),
                new OpenLayers.Control.PanPanel({slideFactor: Math.round(mapWidth / 8)}),
                new OpenLayers.Control.ZoomBox(),
                new OpenLayers.Control.ScaleLine(),
                new OpenLayers.Control.ZoomPanel()
            ]
          });*/
          //map = new Map("viewer", {lon: 0, lat: 0, zoom:zoom});
          global.map.touchMap.addLayer(new OpenLayers.Layer.OSM());
          global.map.setMarkersLayer(new OpenLayers.Layer.Markers("markers"));
		  global.mapClick = new OpenLayers.Control.Click();
          global.map.touchMap.addControl(global.mapClick);
          global.map.centerTo(global.coordinates.lon, global.coordinates.lat, global.zoom);
          //handles displaying hint     
          global.map.init();   
		  global.floatWidget = new FloatWidget('.floaty');
		  global.dialogWindow = new DialogWindow('.dialogWindow', {align: 'top', spacing: 0});
		  global.waitingWidget = new WaitingWidget('.floaty');
		  global.editForm = new EditForm('#poiEditForm');
		  global.newPoiMarker.init(global.map);
		  global.newPoiMarker.iconWidth = 32;
		  global.newPoiMarker.iconHeight = 32;
		  global.currentLocationMarker.init(global.map);
		  global.currentLocationMarker.iconWidth = 16;
		  global.currentLocationMarker.iconHeight = 16;
		  //function controls checking and unchecking follow property
		  $("#followBtn").click(function() {
		  	if (!global.follow) {
		  		$("#followBtn").css('background-image', checkedFollowBtnBackgroundImage);
		  		global.follow = true;
		  		global.map.centerTo(global.coordinates.lon, global.coordinates.lat);
			} else {
		  		$("#followBtn").css('background-image', uncheckedFollowBtnBackgroundImage);
		  		global.follow = false;
		  	}
		  })
		  //checks (and sets) if follow checkbox should be checked
		  if (!global.follow) {
		  	$("#followBtn").css('background-image', uncheckedFollowBtnBackgroundImage);
		  } else {
		  	$("#followBtn").css('background-image', checkedFollowBtnBackgroundImage);
		  }
		  
		  $("#addPoiBtn").click(function(){
			  global.poi = new Poi();
			  global.poi.lon = global.coordinates.lon;
			  global.poi.lat = global.coordinates.lat;
			  global.newPoiMarker.putOnMap(global.coordinates.lon, global.coordinates.lat);
			  global.poi.marker = global.newPoiMarker;
			  displayEditPoisBtns();
			  global.floatWidget.display(message.floats.putPoiHint);
		  });
		  $("#cancelBtn").click(function() {
			  global.poi = null;
			  global.newPoiMarker.hide();
			  displayEditPoisBtns();
		  })
		  
		  $("#pickUpCategoryList li").click(function() {
			  preparePickUpTypesScreen($(this).children("a").children().text());
		  });
		  $("#goToAddFrom").click(function(){
			  global.editForm.clear();
			  stopGeotracking();
			  jqt.goTo("#editingScreen");
		  });

		  $("#poiSaveBtn").click(function(){
		       savePoi();
		  })
		  
		  $("#poiEditSaveBtn").click(function() {
			  saveEditedPoi();
		  });
		  $('#poiForm').submit(function() {
			  saveEditedPoi();
			  return false;
		  })
		  
		  $("#aboutBtn").click(function() {
			  jqt.goTo("#aboutScreen");
		  });
		  
		  $('.showMoreBtn').click(function(){
			  children = $(this).parent().children(".showableField");
			  if (children.hasClass('hidden')) {
				  children.removeClass('hidden');
			  } else {
				  children.addClass('hidden');
		      }
		  });

		  $('#loginBtn').click(function() {
			  logToServer();
		  });
		  $('#loginForm').submit(function() {
			  $('#loginArea input.inputForm').blur();
			  $('#loginBtn').click();
			  return false;
		  })
		  //panel control, uses openLayers methods
		  $(".olControlPanEast").click(function(){
			global.map.touchMap.pan(Math.round($('#viewer').innerWidth() / 4),0,{animate:true});
		  })
		  $(".olControlPanWest").click(function(){
			global.map.touchMap.pan(-Math.round($('#viewer').innerWidth() / 4),0,{animate:true});
		  })
		  $(".olControlPanNorth").click(function(){
			global.map.touchMap.pan(0,-Math.round($('#viewer').innerHeight() / 4),{animate:true});
		  })
		  $(".olControlPanSouth").click(function(){
			global.map.touchMap.pan(0,Math.round($('#viewer').innerHeight() / 4),{animate:true});
		  })

		  $('#appName').text(app.name);
		  $('#appAuthor').text(app.author);
		  $('#appVersion').text(app.version);
		  
		  runApp();
	      setInterval("runApp()", settings.appFrequency);
	    }
  </script>
</head>
<body onload="init();" class="theme"
	style="background: -webkit-gradient(linear, 0% 0, 0% 100%, from(#333), to(#5E5E65) )">
<div id="mapScreen">
	<div class="toolbar">
	<h1>POI Collector</h1>
	<a id="logoutBtn" href="#loginScreen" class="back">Logout</a> <span
	id="cancelBtn" class="back hide">Cancel</span> 
	<span id="goToAddFrom" class="button slideup hide">Edit POI</span></div>
		<div id="viewer"> 
		</div> 
	<ul class="individual">
		<li id="addPoiBtn" style="cursor: pointer">
		<span style="color: #FFFFFF">Add Poi</span></li>
		<li id="followBtn"
		style="text-align: left; cursor: pointer; vertical-align: middle; background-position: 96% 40%; background-repeat: no-repeat;"><span
		style="padding-left: 10px; color: #FFFFFF">Follow</span></li>
	</ul>
</div>
<div id="editingScreen">
	<div class="toolbar">
	<h1>POI data</h1>
	<a href="#mapScreen" class="back">Cancel</a> 
	<span id="poiEditSaveBtn" class="button">Save</span></div>
	<div id="poiEditForm">
	<form id="poiForm">
	<ul class="edit">
		<li class="formRow">Name<input type="text" name="name"
		class="inputForm" /></li>
		<li class="arrow formRow"><a href="#categoryScreen"
		class="slideup">Type<span id="typeName" style="margin-left: 10px"></span><span id="typeValue" style="display: none"></span>
		<span id="typeTag" style="display: none"></span>
		</a></li>
		<li class="formRow">Address
		<ul class="edit">
			<li class="formRow">Street<input type="text" class="inputForm"
			name="street" /></li>
			<li class="formRow">House number<input type="text"
			class="inputForm" name="houseNumber" /></li>
			<li class="formRow arrow down showMoreBtn">More...</li>
			<li class="formRow showableField hidden">Postal code<input
			type="text" class="inputForm" name="postCode" /></li>
			<li class="formRow showableField hidden">Phone<input type="text"
			class="inputForm" name="phone" /></li>
			<li class="formRow showableField hidden">Website<input
			type="text" class="inputForm" name="website" /></li>
		</ul>
		</li>
		<li class="formRow">Info
		<ul class="edit">
			<li class="formRow">description<textarea type="text"
			class="inputForm" name="description"></textarea></li>
		</ul>
		</li>
		<li>
		<ul class="edit moreTags">
			<li class="formRow arrow down showMoreBtn moreTags">More tags...</li>
		</ul>
		</li>
	</ul>
	<input type="submit" style="display:none" />
	</form>
	</div>
</div>
<div id="categoryScreen">
	<div class="toolbar">
	<h1>Categories</h1>
	<a href="#editingScreen" class="back">Back</a>
	</div>
	<ul id="pickUpCategoryList">
	</ul>
</div>
<div id="typeScreen">
	<div class="toolbar">
	<h1>Types</h1>
	<a href="#categoryScreen" class="back">Back</a></div>
	<ul id="pickUpTypeList">
	</ul>
</div>
<div id="aboutScreen">
	<div class="toolbar">
		<h1>About</h1>
		<a id="logoutBtn" href="#loginScreen" class="back">back</a>
	</div>
	<ul>
		<li>Application name: <span id="appName"></span></li>
		<li>Author: <span id="appAuthor"></span></li>
		<li>Version: <span id="appVersion"></span></li>
		<li><a href="http://wiki.openstreetmap.org/wiki/Mobile_POI_collector" target="_blank">OSM wiki page</a></li>
		<li><a href="http://code.google.com/p/osmmobilepoicollector/" target="_blank">Project page</a></li>
		<li><a href="http://code.google.com/p/osmmobilepoicollector/issues/list" target="_blank">Report issue</a></li>
	</ul>
</div>
<div id="loginScreen" class="current">
	<div class="toolbar">
	<h1>POI Collector</h1>
		<span id="aboutBtn" class="button">About App</span>
	</div>
	<form id="loginForm">
	<ul id="loginArea" class="edit">
		<li class="formRow">Username<input type="text" class="inputForm"
		name="login" /></li>
		<li class="formRow">Password<input type="password"
		class="inputForm" name="password" /></li>
		<li id="loginBtn" class="btn">Login</li>
		<input type="submit" style="display:none" />
	</ul>
	</form>
</div>


<div class="floaty" style="display: none">
</div>

<div class="dialogWindow" style="display: none">
	<h1>POI data</h1>
	<ul>
		<li>Id: <span id="poiDataId"></span></li>
		<li>Name: <span id="poiDataName"></span></li>
		<li>Type: <span id="poiDataType"></span></li>
	</ul>
	<ul class="individual">
		<li class="editBtn">Edit</li>
		<li class="cancelBtn">Cancel</li>
	</ul>
</div>

</body>
</html>
